<script setup>
import { onMounted, watch } from 'vue'
import { listMapData } from '@/api/MapData/MapData'
import { getBoundary } from '@/api/boundary/boundary'
var boundaryMap = ''
var polygon = ''
const emit = defineEmits(['change'])
const props = defineProps({
  config: {
    type: Object,
    default: () => ({
      color: '#1495E7',
      weight: 3,
      opacity: 0.5,
      fillColor: '#FFFFFF',
      fillOpacity: 0.5,
    }),
  },
  id: {
    type: Number,
    default: null,
  },
})
const isFirst = ref(true)
const isEdit = ref(true)
const points = ref([])
const boundaryId = ref(null)
watch(
  () => points.value,
  (newPoints) => {
    emit('change', newPoints)
  },
  { deep: true }
)
// 撤销上一次编辑
function withdrawLastEdit() {
  if (points.value.length > 0) {
    points.value.pop()
    boundaryMap.removeOverLay(polygon)
    polygon = ''
    if (points.value.length > 0) {
      polygon = new T.Polygon(points.value, props.config)
      boundaryMap.addOverLay(polygon)
    }
  }
}
onMounted(() => {
  init()
})
// 清空边界
function clearBoundary() {
  if (boundaryMap) {
    points.value = []
    if (polygon) {
      boundaryMap.removeOverLay(polygon)
      polygon = ''
    }
    if (poly) {
      boundaryMap.removeOverLay(poly)
      poly = ''
    }
  }
}
function init(id) {
  boundaryId.value = id
  if (isFirst.value) {
    console.log('init')
    listMapData({ pageNum: 1, pageSize: 10 }).then((response) => {
      var zoom = 12
      const center = response.rows[0].position.split(',')
      const position = {
        lng: parseFloat(center[0]),
        lat: parseFloat(center[1]),
      }
      boundaryMap = new T.Map('boundaryMap')
      boundaryMap.centerAndZoom(new T.LngLat(position.lng, position.lat), zoom)
      const imageURL =
        'http://t0.tianditu.gov.cn/img_w/wmts?' +
        'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
        '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8bce5ceb483255b37a4aaa52bc86d11e'
      const imageURLT =
        'http://t0.tianditu.gov.cn/cia_w/wmts?' +
        'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
        '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}' +
        '&tk=8bce5ceb483255b37a4aaa52bc86d11e'
      //创建自定义图层对象
      var lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
      var textLayer = new T.TileLayer(imageURLT, {
        minZoom: 1,
        maxZoom: 18,
      })
      //将图层增加到地图上
      boundaryMap.addLayer(lay)
      boundaryMap.addLayer(textLayer)
      boundaryMap.addEventListener('click', (e) => {
        if (!isEdit.value) return
        points.value.push(new T.LngLat(e.lnglat.getLng(), e.lnglat.getLat()))
        if (polygon) {
          boundaryMap.removeOverLay(polygon)
          polygon = ''
        }
        //创建面对象
        polygon = new T.Polygon(points.value, {
          color: 'blue',
          weight: 3,
          opacity: 0.5,
          fillColor: '#FFFFFF',
          fillOpacity: 0.5,
        })
        //向地图上添加面
        boundaryMap.addOverLay(polygon)
        emit('change', points.value)
      })
      function loadGeoJson() {
        var countries = []
        var countriesOverlay = new T.D3Overlay(init, redraw)
        d3.json(
          'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/%E7%9F%B3%E6%A2%81%E9%95%87.geojson?sign=tqAPonliYDiMECn1umfHzl88RGiZMsxs_9MPGRfjbSs=:0',
          function (data) {
            countries = data.features
            boundaryMap.addOverLay(countriesOverlay)
            countriesOverlay.bringToBack()
          }
        )
        function init(sel, transform) {
          var upd = sel.selectAll('path.geojson').data(countries)
          upd
            .enter()
            .append('path')
            .attr('class', 'geojson')
            .attr('stroke', 'black')
            .attr('fill', function (d, i) {
              return d3.hsl(Math.random() * 360, 0.9, 0.5)
            })
            .attr('fill-opacity', '0.5')
        }

        function redraw(sel, transform) {
          sel.selectAll('path.geojson').each(function (d, i) {
            d3.select(this).attr('d', transform.pathFromGeojson)
          })
        }
      }
      loadGeoJson()
      if (props.id) {
        isEdit.value = false
        addOverLay(props.id)
      }
    })
    isFirst.value = false
  } else {
    clearBoundary()
    if (id) {
      isEdit.value = false
      addOverLay(id)
    } else {
      isEdit.value = true
    }
  }
}
var poly = null
function addOverLay(id) {
  getBoundary(id).then((response) => {
    if (response.data) {
      points.value = JSON.parse(response.data.position)
      boundaryId.value = response.data.id
      if (poly) {
        boundaryMap.removeOverLay(poly)
      }
      poly = new T.Polygon(points.value, props.config)
      boundaryMap.addOverLay(poly)
    } else {
      points.value = []
    }
  })
}
defineExpose({
  init,
})
</script>
<template>
  <div id="boundaryMap"></div>
  <div v-if="!boundaryId" class="boundary-actions">
    <el-button type="primary" @click="withdrawLastEdit"
      >撤销上一次编辑</el-button
    >
    <el-button type="primary" @click="clearBoundary">清空边界</el-button>
  </div>
</template>
<style lang="scss" scoped>
#boundaryMap {
  width: 100%;
  height: 300px;
  position: relative;
  margin-bottom: 10px;
}
</style>
